package cn.cms.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class UrlUtil {

	public static String downloadPic(String inputPicUrl, String outPicPath) {
		URL url;
		try {
			url = new URL(inputPicUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(3000);//毫秒
			InputStream is = url.openStream();
			String picName = inputPicUrl.substring(inputPicUrl.lastIndexOf("/")+1);
			File outPath = new File(outPicPath);
			if (!outPath.exists()) {
				outPath.mkdir();
			}
			File outFile = new File(outPicPath+"/"+picName);
			OutputStream os = new FileOutputStream(outFile);
			byte[] buff = new byte[1024];
			while (true) {
				int readed = is.read(buff);
				if (readed == -1) {
					break;
				}
				byte[] temp = new byte[readed];
				System.arraycopy(buff, 0, temp, 0, readed);
				os.write(temp);
			}
			is.close();
			os.close();
			return picName;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	public static String getUrlDate(String urlStr) {
		InputStream in = null;
		try {
			
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(3000);//毫秒
			try{
				in = url.openStream();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			String content = pipe(in,"utf-8");
			in.close();
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 
	 * @param urlStr
	 * @param filePath
	 * @return
	 */
	public static String getUrlDate(String urlStr, String filePath) {
		InputStream in = null;
		PrintWriter pw = null;
		try {
			
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setReadTimeout(60000);
			conn.setConnectTimeout(60000);//毫秒
			try{
				in = url.openStream();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			String content = pipe(in,filePath,"utf-8",pw);
			in.close();
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	/**
	 * 
	 * @param urlStr
	 * @param filePath
	 * @return
	 */
	public static String getUrlDate(String urlStr, String filePath, String charset) {
		InputStream in = null;
		PrintWriter pw = null;
		try {
			
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setReadTimeout(60000);
			conn.setConnectTimeout(60000);//毫秒
			try{
				in = url.openStream();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			String content = pipe(in,filePath,charset ,pw);
			in.close();
			return content;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	static String pipe(InputStream in, String charset) throws IOException {
        StringBuffer s = new StringBuffer();
        if(charset==null||"".equals(charset)){
        	charset="utf-8";
        }
        String rLine = null;
        BufferedReader bReader = new BufferedReader(new InputStreamReader(in,charset));
        
        if(in != null){
	        while ( (rLine = bReader.readLine()) != null) {
	            String tmp_rLine = rLine;
	            int str_len = tmp_rLine.length();
	            if (str_len > 0) {
	              s.append(tmp_rLine);
	            }
	            tmp_rLine = null;
	        }
        }
       
        return s.toString();
	}
	
	/**
	 * 
	 * @param in
	 * @param filePath
	 * @param charset
	 * @param pw
	 * @return
	 * @throws IOException
	 */
	static String pipe(InputStream in, String filePath, String charset, PrintWriter pw) throws IOException {
        StringBuffer s = new StringBuffer();
        if(charset==null||"".equals(charset)){
        	charset="utf-8";
        }
        String rLine = null;
        BufferedReader bReader = new BufferedReader(new InputStreamReader(in,charset));
        
        
		FileOutputStream fo = new FileOutputStream(filePath);
		OutputStreamWriter writer = new OutputStreamWriter(fo, charset);
		pw = new PrintWriter(writer);
        while ( (rLine = bReader.readLine()) != null) {
            String tmp_rLine = rLine;
            int str_len = tmp_rLine.length();
            if (str_len > 0) {
              s.append(tmp_rLine);
              pw.println(tmp_rLine);
              pw.flush();
            }
            tmp_rLine = null;
       }
       
        return s.toString();
	}

	public static String getUrlDateTwo(String reqUrl) {
		String parameters = "";
		HttpURLConnection url_con = null;
		String responseContent = null;
		try {
			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
			url_con.setRequestProperty("Accept", "application/json");// 接收json字符串
			url_con.setRequestProperty("Content-Type", "application/json");// 请求参数
			url_con.setConnectTimeout(50);// （单位：毫秒）jdk
			// 1.5换成这个,连接超时
			url_con.setReadTimeout(50);// （单位：毫秒）jdk 1.5换成这个,读操作超时
			url_con.setDoOutput(true);

			byte[] b = parameters.getBytes();
			url_con.getOutputStream().write(b, 0, b.length);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
			// url_con.connect();
			InputStream in = url_con.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(in,
					"utf-8"));

			String tempLine = rd.readLine();

			StringBuffer tempStr = new StringBuffer();
			String crlf = System.getProperty("line.separator");// 改平台下行与行的分隔符
			while (tempLine != null) {// 循环获取数据
				tempStr.append(tempLine);
				tempStr.append(crlf);
				tempLine = rd.readLine();
			}
			responseContent = tempStr.toString();
			rd.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
		return responseContent;
	}
	
	public static String getUrl(String urlStr) {
		InputStream in = null;
		HttpURLConnection url_con = null;
		try {
			
			URL url = new URL(urlStr);
			url_con = (HttpURLConnection)url.openConnection();
			url_con.setDoOutput(true);
			url_con.setConnectTimeout(100);//毫秒
			url_con.setReadTimeout(100);
			try{
				in = url.openStream();
			}catch (Exception e) {
				e.printStackTrace();
				return "";
			}
			
			String content = pipe(in,"utf-8");
			in.close();
			return content;
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
	}
}